package com.baichang.taoshunda.service.impl;

import com.baichang.framework.excelption.ServiceException;
import com.baichang.taoshunda.dao.*;
import com.baichang.taoshunda.entity.*;
import com.baichang.taoshunda.entity.em.BackOrderState;
import com.baichang.taoshunda.entity.em.CompanyBalanceState;
import com.baichang.taoshunda.entity.em.OrderState;
import com.baichang.taoshunda.service.*;
import com.baichang.taoshunda.utils.UserPushMsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by ${wushenglu} on 2018/3/13.
 */
@Service
public class ReservationOrderServiceImpl implements ReservationOrderService {
    @Autowired
    private ReservationOrderDao reservationOrderDao;
    @Autowired
    private OrderStateDao orderStateDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    BusinessService businessService;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private PensionService pensionService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailsDao orderDetailsDao;
    @Autowired
    private RebateService rebateService;

    @Override
    public boolean saveReservationOrder(ReservationOrder reservationOrder) {
        return reservationOrderDao.save(reservationOrder) > 0;
    }

    @Override
    public boolean userConsumeOrder(String orderNumber, Integer id) throws ServiceException {
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (Objects.equals(order.getOrderState(), OrderState.待付款.getCode())) {
            throw new ServiceException("请先付款在进行消费！");
        }
        ReservationOrder reservationOrder = reservationOrderDao.getEntityById(id);
        if (reservationOrder.getOrderState() == 1) {
            throw new ServiceException("请确认一下订单状态，该订单已确认消费");
        }
        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        UserPushMsgUtil.userConsumeOrder(order.getId(), order.getBuyerId(), bussiness.getAccount(), orderNumber, order.getOrderType());
        return reservationOrderDao.updateUserStatus(id);
    }

    /**
     * 查看预约订单详情
     *
     * @param orderNumber
     * @return
     */
    @Override
    public List<Map<String, Object>> findReservationOrder(String orderNumber) {
        return reservationOrderDao.findReservationOrder(orderNumber);
    }

    @Override
    public boolean companyConsumeOrder(String orderNumber, Integer id) throws ServiceException {
        boolean flag = false;
        ReservationOrder reservationOrder = reservationOrderDao.getEntityById(id);
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (reservationOrder.getOrderState() == 0) {
            throw new ServiceException("请确认一下订单状态，用户未消费不能确认消费");
        }
        if (reservationOrder.getOrderState() == 2) {
            throw new ServiceException("请确认一下订单状态，该订单已确认消费");
        }
        int count = reservationOrderDao.getCountByNumber(orderNumber);
        if (count > 0) {
            if (count == 1) {
                flag = reservationOrderDao.updateCompanyStatus(id);
                if (flag) {
                    flag = updateOrderState(OrderState.待评价, BackOrderState.未退款, order.getId());
                    String blanceState = "+";
                    int souceType = 1;
                    orderDao.updateEndtime(id);
                    //添加商家余额跟账单
//        businessService.updateBussinessBalance(order.getSellerId(), order.getGoodsAllMoney().doubleValue(), CompanyBalanceState.订单完成.getCode(), order.getOrderNumber());
                    businessService.updateBussinessBalance(order.getSellerId(), order.getBussGetMoney().doubleValue(), CompanyBalanceState.订单完成.getCode(), order.getOrderNumber(), order.getRefunds());
                }
                User user = userService.getUserBeanById(order.getBuyerId());
                if (user != null) {
                    if (user.getIsCertificate() == 1) {
                        OrderDetails orderdetail = orderDetailsDao.getGoodsByOrderNumber(order.getOrderNumber(),1);
                        int number = orderDetailsDao.getGoodsNUmberByOrderNumber(order.getOrderNumber());
                        String goodsName = "";
                        if (number > 1) {
                            goodsName = orderdetail.getGoodsName() + "等多件商品";
                        } else {
                            goodsName = orderdetail.getGoodsName();
                        }
                        pensionService.savePension(order.getBuyerId(), goodsName, 1, orderdetail.getGoodsSpec(), order.getOrderNumber(),
                                order.getGoodsAllMoney().divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), order.getAllMoney(),
                                order.getAllMoney().divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), 1,
                                order.getSellerId(), order.getPayType(), order.getGoodsAdress(), order.getRedPacketMoney(),orderdetail.getGoodsId());
                    }
                }
                rebateService.addRebate(order.getSellerId(), order.getOrderNumber(), 1);
            } else {
                //存在多个未消费订单直接修改为消费
                flag = reservationOrderDao.updateCompanyStatus(id);
            }
            goodsDao.updateSaleNum(reservationOrder.getGoodsId(), 1);
        }
        return flag;
    }

    @Override
    public int getCountByOrder(String orderNumber) {
        return reservationOrderDao.getCountByOrder(orderNumber);
    }

    @Override
    public int getCountByOrderAndState0(String orderNumber) {
        return reservationOrderDao.getCountByOrderAndState0(orderNumber);
    }

    @Override
    public void updateOrderState(String orderNumber) {
        reservationOrderDao.updateOrderState(orderNumber);
    }

    @Override
    public double getAllMoneyByOrder(String orderNumber) {
        return reservationOrderDao.getAllMoneyByOrder(orderNumber);
    }

    /**
     * 修改订单状态
     *
     * @param orderState 订单状态
     * @param orderId    订单编号
     * @return
     */
    public boolean updateOrderState(OrderState orderState, BackOrderState backOrderState, Integer orderId) {
        OrderStates states = new OrderStates();
        states.setCreated(new Date());
        states.setOrderState(orderState.getCode());
        states.setOrderId(orderId);
        orderStateDao.save(states);
        return orderDao.updateOrderAllState(orderId, orderState.getCode(), backOrderState.getCode()) > 0;
    }
}
